<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="70%">
    <!-- 基本信息 -->
    <el-descriptions :column="3" border class="mb-20px">
      <el-descriptions-item label="客户名称" :span="2">
        {{ formData.customerName }}
      </el-descriptions-item>
      <el-descriptions-item label="客户来源">
        <dict-tag :type="DICT_TYPE.OA_CUSTOMER_SOURCE" :value="formData.sourceId || ''" />
      </el-descriptions-item>
      <el-descriptions-item label="所属行业">
        <dict-tag :type="DICT_TYPE.OA_INDUSTRY" :value="formData.industryId || ''" />
      </el-descriptions-item>
      <el-descriptions-item label="客户等级">
        <dict-tag :type="DICT_TYPE.OA_CUSTOMER_LEAVE" :value="formData.levelId || ''" />
      </el-descriptions-item>
      <el-descriptions-item label="客户意向">
        <dict-tag :type="DICT_TYPE.OA_INTENT" :value="formData.intentId || ''" />
      </el-descriptions-item>
      <el-descriptions-item label="创建者">
        {{ formData.creatorName }}
      </el-descriptions-item>
      <el-descriptions-item label="更新者">
        {{ formData.updaterName }}
      </el-descriptions-item>
      <el-descriptions-item label="联系地址" :span="2">
        {{ formData.address }}
      </el-descriptions-item>
      <el-descriptions-item label="客户介绍" :span="3">
        {{ formData.introduction }}
      </el-descriptions-item>
      <el-descriptions-item label="主要经营业务" :span="3">
        {{ formData.business }}
      </el-descriptions-item>
      <el-descriptions-item label="备注" :span="3">
        {{ formData.remarks }}
      </el-descriptions-item>
      
    </el-descriptions>

    <!-- Tab标签页 -->
    <el-tabs v-model="activeTab" type="border-card">
      

      <!-- 跟进记录 Tab -->
      <el-tab-pane label="跟进记录" name="follow">
        <ContentWrap>
          <div class="mb-10px">
            <el-button
              type="primary"
              @click="openFollowUpForm"
              v-hasPermi="['oa:customer:create']"
            >
              <Icon icon="ep:plus" /> 新增跟进记录
            </el-button>
          </div>
          <el-table
            v-loading="followUpLoading"
            :data="followUpList"
          >
            <el-table-column label="编号" align="center" prop="id" width="60" />
            <el-table-column label="联系人" align="center" prop="contactName" width="100" />
            <el-table-column label="跟进时间" align="center" prop="followTime" width="120">
              <template #default="scope">
                <span>{{ formatDate(scope.row.followTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="跟进方式" align="center" prop="followMethod" width="100">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.OA_CUSTOMER_FOLLOW_METHOD" :value="scope.row.followMethod" />
              </template>
            </el-table-column>
            
            <el-table-column label="沟通内容" align="center" prop="content" :show-overflow-tooltip="true" />
            <el-table-column label="下次沟通时间" align="center" prop="nextContactTime" width="180">
              <template #default="scope">
                <span>{{ formatDate(scope.row.nextContactTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="150" fixed="right">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="handleEditFollowUp(scope.row)"
                  v-hasPermi="['oa:customer:update']"
                >
                  编辑
                </el-button>
                <el-button
                  link
                  type="danger"
                  @click="handleDeleteFollowUp(scope.row.id)"
                  v-hasPermi="['oa:customer:delete']"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <Pagination
            v-model:total="followUpTotal"
            v-model:page="followUpQueryParams.pageNo"
            v-model:limit="followUpQueryParams.pageSize"
            @pagination="getFollowUpList"
          />
        </ContentWrap>
      </el-tab-pane>

      <!-- 销售线索 Tab -->
      <el-tab-pane label="销售线索" name="salesLead">
        <ContentWrap>
          <div class="mb-10px">
            <el-button
              type="primary"
              @click="openSalesLeadForm"
              v-hasPermi="['oa:customer:create']"
            >
              <Icon icon="ep:plus" /> 新增销售线索
            </el-button>
          </div>
          <el-table
            v-loading="salesLeadLoading"
            :data="salesLeadList"
          >
            <el-table-column label="序号" align="center" prop="id" />
            <el-table-column label="归属人员" align="center" prop="ownerName" />
            <el-table-column label="机会主题" align="center" prop="opportunityTitle" />
            <el-table-column label="发现时间" align="center" prop="discoveryTime" width="180">
              <template #default="scope">
                <span>{{ formatDate(scope.row.discoveryTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="预计签单时间" align="center" prop="estimatedSignTime" width="180">
              <template #default="scope">
                <span>{{ formatDate(scope.row.estimatedSignTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="预计签单金额" align="center" prop="estimatedAmount" />
            
            <el-table-column label="操作" align="center" width="150" fixed="right">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="handleEditSalesLead(scope.row)"
                  v-hasPermi="['oa:customer:update']"
                >
                  编辑
                </el-button>
                <el-button
                  link
                  type="danger"
                  @click="handleDeleteSalesLead(scope.row.id)"
                  v-hasPermi="['oa:customer:delete']"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <Pagination
            v-model:total="salesLeadTotal"
            v-model:page="salesLeadQueryParams.pageNo"
            v-model:limit="salesLeadQueryParams.pageSize"
            @pagination="getSalesLeadList"
          />
        </ContentWrap>
      </el-tab-pane>

      <!-- 联系人信息 Tab -->
      <el-tab-pane label="联系人信息" name="contact">
        <ContentWrap>
          <contact-person-list :customer-id="formData.id" />
        </ContentWrap>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </template>
  </Dialog>

  <!-- 跟进记录表单弹窗 -->
  <CustomerFollowUpForm ref="followUpFormRef" @success="getFollowUpList" />

  <!-- 销售线索表单弹窗 -->
  <SalesLeadForm ref="salesLeadFormRef" @success="getSalesLeadList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { CustomerApi, CustomerVO } from '@/api/oa/customer'
import ContactPersonList from './components/ContactPersonList.vue'
import { CustomerFollowUpApi } from '@/api/oa/customerfollowup'
import { SalesLeadApi } from '@/api/oa/saleslead'
import CustomerFollowUpForm from '@/views/oa/customerfollowup/CustomerFollowUpForm.vue'
import SalesLeadForm from '@/views/oa/saleslead/SalesLeadForm.vue'
import { formatDate } from '@/utils/formatTime'

/** 客户详情 表单 */
defineOptions({ name: 'CustomerDetail' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const activeTab = ref('follow') // 当前激活的Tab
const formData = ref<CustomerVO>({
  id: 0,
  customerName: '',
  sourceId: undefined,
  address: '',
  industryId: undefined,
  levelId: undefined,
  statusId: undefined,
  intentId: undefined,
  introduction: '',
  business: '',
  contactName: '',
  phone: '',
  gender: undefined,
  email: '',
  wechat: '',
  qq: '',
  remarks: '',
  creatorName: '',
  updaterName: '',
})

const followUpLoading = ref(false) // 跟进记录列表的加载中
const followUpList = ref([]) // 跟进记录列表的数据
const followUpTotal = ref(0) // 跟进记录列表的总页数
const followUpQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  customerId: 0
})
const followUpFormRef = ref() // 跟进记录表单组件引用

const salesLeadLoading = ref(false) // 销售线索列表的加载中
const salesLeadList = ref([]) // 销售线索列表的数据
const salesLeadTotal = ref(0) // 销售线索列表的总页数
const salesLeadQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  customerId: 0
})
const salesLeadFormRef = ref() // 销售线索表单组件引用

/** 打开弹窗 */
const open = async (id: number) => {
  dialogVisible.value = true
  dialogTitle.value = '客户详情'
  formLoading.value = true
  // 重置表单数据
  formData.value = {
    id: 0,
    customerName: '',
    sourceId: undefined,
    address: '',
    industryId: undefined,
    levelId: undefined,
    statusId: undefined,
    intentId: undefined,
    introduction: '',
    business: '',
    contactName: '',
    phone: '',
    gender: undefined,
    email: '',
    wechat: '',
    qq: '',
    remarks: '',
    creatorName: '',
    updaterName: '',
  }
  // 重置当前激活的Tab
  activeTab.value = 'follow'
  try {
    formData.value = await CustomerApi.getCustomer(id)
    activeTab.value = 'follow'
  } catch (error) {
    message.error('获取客户详情失败')
  } finally {
    formLoading.value = false
  }
}

/** 获取跟进记录列表 */
const getFollowUpList = async () => {
  followUpLoading.value = true
  try {
    followUpQueryParams.customerId = formData.value.id
    const data = await CustomerFollowUpApi.getCustomerFollowUpPage(followUpQueryParams)
    followUpList.value = data.list
    followUpTotal.value = data.total
  } finally {
    followUpLoading.value = false
  }
}

/** 打开跟进记录表单 */
const openFollowUpForm = () => {
  followUpFormRef.value?.open('create', undefined, {
    customerId: formData.value.id,
    customerName: formData.value.customerName
  })
}

/** 编辑跟进记录 */
const handleEditFollowUp = (row: any) => {
  followUpFormRef.value?.open('update', row.id, {
    customerId: formData.value.id,
    customerName: formData.value.customerName
  })
}

/** 删除跟进记录 */
const handleDeleteFollowUp = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CustomerFollowUpApi.deleteCustomerFollowUp(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getFollowUpList()
  } catch {}
}

/** 获取销售线索列表 */
const getSalesLeadList = async () => {
  salesLeadLoading.value = true
  try {
    salesLeadQueryParams.customerId = formData.value.id
    const data = await SalesLeadApi.getSalesLeadPage(salesLeadQueryParams)
    salesLeadList.value = data.list
    salesLeadTotal.value = data.total
  } finally {
    salesLeadLoading.value = false
  }
}

/** 打开销售线索表单 */
const openSalesLeadForm = () => {
  salesLeadFormRef.value?.open('create', undefined, {
    customerId: formData.value.id,
    customerName: formData.value.customerName
  })
}

/** 编辑销售线索 */
const handleEditSalesLead = (row: any) => {
  salesLeadFormRef.value?.open('update', row.id, {
    customerId: formData.value.id,
    customerName: formData.value.customerName
  })
}

/** 删除销售线索 */
const handleDeleteSalesLead = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SalesLeadApi.deleteSalesLead(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getSalesLeadList()
  } catch {}
}

// 监听 customerId 变化
watch(() => formData.value.id, (val) => {
  if (val) {
    getFollowUpList()
    getSalesLeadList()
  }
})

// 监听弹窗关闭
watch(dialogVisible, (val) => {
  if (!val) {
    // 关闭弹窗时重置数据
    formData.value = {
      id: 0,
      customerName: '',
      sourceId: undefined,
      address: '',
      industryId: undefined,
      levelId: undefined,
      statusId: undefined,
      intentId: undefined,
      introduction: '',
      business: '',
      contactName: '',
      phone: '',
      gender: undefined,
      email: '',
      wechat: '',
      qq: '',
      remarks: '',
      creatorName: '',
      updaterName: '',
    }
    activeTab.value = 'follow'
  }
})

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>

<style scoped>
:deep(.el-descriptions__label) {
  width: 120px;
  font-weight: bold;
}
:deep(.el-descriptions__content) {
  word-break: break-all;
}
.mb-20px {
  margin-bottom: 20px;
}
.detail-tabs {
  margin-top: 10px;
}
:deep(.el-tabs__content) {
  padding: 20px;
}
.empty-block {
  padding: 40px 0;
}
</style> 